<template>
  <el-dialog
    ref="dialogDom"
    :title="title"
    :visible.sync="open"
    width="800px"
    append-to-body
    :close-on-click-modal="false"
    @close="closeModal"
  >
    <el-form ref="form" :model="form" :show-message="false" label-width="110px">
      <el-form-item label="处方名称" prop="name" required>
        <el-input
          v-model.trim="form.name"
          placeholder="请输入处方名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="处方分类" prop="type" required>
        <el-select v-model="form.type" placeholder="请选择">
          <el-option label="经典方" :value="1"></el-option>
          <el-option label="协定方" :value="2"></el-option>
          <!-- <el-option label="医师方" :value="3"></el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item label="处方类型" prop="prescriptionType" required>
        <el-select
          v-model="form.prescriptionType"
          placeholder="请选择"
          @change="changePrescriptionType"
        >
          <el-option
            v-for="dict in dict.type.tcm_prescript_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="功效" prop="effect">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入处方功效"
          v-model="form.effect"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="主治" prop="mainTreat">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入处方主治功能"
          v-model="form.mainTreat"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="处方来源" prop="source">
        <el-input placeholder="请输入处方来源" v-model="form.source">
        </el-input>
      </el-form-item>
      <el-form-item label="用法" prop="usage">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入处方用法"
          v-model="form.usage"
        >
        </el-input>
      </el-form-item>

      <div
        v-for="(item, index) in form.materialsItems"
        :key="index"
        :class="{ forBox: form.prescriptionType == 1 }"
      >
        <div class="disFlx">
          <el-tag
            v-if="form.prescriptionType == 1"
            type="warning"
            effect="dark"
            class="sortTag shrink0"
            >贴{{ index + 1 }}</el-tag
          >
          <div class="disFlx" style="flex: 1">
            <div class="formItemTitle shrink0">添加药材</div>
            <SearchDrug
              v-if="open"
              @change="(val) => handDrugChange(val, index)"
            />
          </div>
          <div v-if="form.prescriptionType == 1" class="ml-10 shrink0">
            <el-button
              v-if="form.materialsItems.length > 1"
              type="danger"
              size="medium"
              @click="removeForBox(index)"
              >删除</el-button
            >
            <el-button type="primary" size="medium" @click="addForBox"
              >新增贴</el-button
            >
          </div>
        </div>

        <el-table
          :data="item.materials"
          border
          class="mt-10"
          @row-contextmenu="(row, column, event) => handleRowContextmenu(row, column, event, index)"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="55"
          />
          <el-table-column
            label="药材名称"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.materialsId">{{row.materialsName}}</span>
              <span v-else class="colorRED fz-12">添加数据将优先填充插入行</span>
            </template>
          </el-table-column>
          <el-table-column label="剂量" align="center" width="100">
            <template slot-scope="{ row }">
              <div class="disFlxAC">
                <el-input-number
                  :controls="false"
                  :precision="form.prescriptionType == 1 ? 2 : 0"
                  :min="0"
                  v-model="row.dose"
                  placeholder="请输入"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="计量单位" align="center" width="120">
            <template slot-scope="{ row }">
              <el-select v-model="row.unitId" placeholder="请选择">
                <el-option
                  v-for="item in unitList"
                  :key="item.unitId"
                  :label="item.unit"
                  :value="item.unitId"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="{ row, $index }">
              <el-button
                size="mini"
                type="text"
                @click="removeRow(index, $index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div v-if="form.prescriptionType == 1" class="mt-10">
          <el-button
            type="success"
            size="mini"
            class="mr-10"
            @click="openAcupointSelect(index)"
            >添加穴位</el-button
          >
          <el-tag
            v-for="acupoints in item.acupoints"
            :key="acupoints.id"
            class="forTag"
            type="warning"
            effect="plain"
          >
            {{ acupoints.acupointName }}
          </el-tag>
        </div>
      </div>
    </el-form>

    <AcupointSelect ref="AcupointSelect" @change="acupointChange" />

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="open = false">取 消</el-button>
    </div>

    <ContextButton
      v-if="menuVisible"
      ref="contextbutton"
      @foo="foo"
      @handleMenu="handleMenu"
    />
  </el-dialog>
</template>

<script>
import {
  addPrescript,
  updatePrescript,
  getPrescriptDetails
} from "@/api/saas/tcm.js";
import SearchDrug from "../drug/searchDrug";
import { getSelectList } from "@/api/system/unit";
import AcupointSelect from '@/views/saas/acupoint/acupointSelect'
import { deepClone } from "@/utils";
import ContextButton from '@/components/ContextButton'

export default {
  components: {
    SearchDrug,
    AcupointSelect,
    ContextButton
  },
  dicts: [
    "tcm_prescript_type"
  ],
  data() {
    return {
      title: "新建处方",
      open: false,
      form: {
        id: undefined,
        name: "",
        type: 1,
        prescriptionType: undefined, // 处方类型
        effect: "", // 功效
        mainTreat: "", // 主治
        usage: "", // 用法
        materialsItems: [{
          acupoints: [], // 穴位
          materials: [], // 药材
        }] // 药材项
      },
      unitList: [],
      currentIndex: 0, // 当前添加的贴敷模板

      menuVisible: false,
      insertIndex: 0, // 插入的当前表格下标
      insertRow: undefined, // 选择插入位置的行
    };
  },
  methods: {
    openModal(row) {
      if (row && row.id) {
        this.title = '编辑处方';
        this.form = deepClone(row);
        getPrescriptDetails(row.id).then(res => {
          const { data } = res;
          this.form.materialsItems = deepClone(data.materialsItems);
        })
      }
      this.open = true;

      getSelectList({ pageNum: 1, pageSize: 999 }).then(res => {
        this.unitList = res.rows;
      })
    },
    closeModal() {
      this.$refs["form"].resetFields();
      Object.assign(this.$data, this.$options.data()); // 存在自定义校验规则不能重置data
    },
    handleRowContextmenu(row, column, event, index) {
      //点击鼠标右键触发
      this.menuVisible = false;
      this.menuVisible = true;
      // 阻止右键默认行为
      event.preventDefault();
      this.$nextTick(() => {
        this.insertIndex = index;
        this.insertRow = row;
        let fdom = this.$refs.dialogDom.$refs.dialog;
        let x_skewing = fdom.offsetLeft;
        let y_skewing = fdom.offsetTop - (fdom.offsetHeight / 2);
        this.$refs.contextbutton.init(row, column, event, x_skewing, y_skewing);
      });
    },
    foo() {
      // 取消鼠标监听事件 菜单栏
      this.menuVisible = false;
      document.removeEventListener("click", this.foo);
    },
     handleMenu(item) {
      const { materials } = this.form.materialsItems[this.insertIndex];
      const cIndex = materials.findIndex(item => item.materialsId === this.insertRow.materialsId);
      const iIndex = item.value === 'top' ? cIndex : cIndex + 1;

      const g = this.unitList.find(v => v.unit === 'g');
      const addRow = {
        materialsId: undefined, // 药材ID
        materialsName: undefined, // 药材名称
        dose: this.form.prescriptionType == 1 ? 0.2 : 10, // 剂量
        unitId: g ? g.unitId : undefined, // 单位ID
      }

      materials.splice(iIndex, 0, addRow);
      this.form.materialsItems[this.insertIndex].materials = materials;
    },

    // 切换处方类型时，药材只保留一组
    changePrescriptionType() {
      this.form.materialsItems.splice(1, this.form.materialsItems.length - 1);
    },
    // 选择药材
    handDrugChange(item, index) {
      const { materials } = this.form.materialsItems[index];

      if (materials.findIndex(v => v.materialsId === item.id) !== -1) {
        this.$message.error(`${item.name} 已经添加过,请勿重复添加`)
        return
      }else if(materials.findIndex(v=> !v.materialsId) !== -1){
        const nullRowIndex = materials.findIndex(v=> !v.materialsId);
        materials[nullRowIndex].materialsId = item.id;
        materials[nullRowIndex].materialsName = item.name;
      }else{
        const g = this.unitList.find(v => v.unit === 'g');
        materials.push({
          materialsId: item.id, // 药材ID
          materialsName: item.name, // 药材名称
          dose: this.form.prescriptionType == 1 ? 0.2 : 10, // 剂量
          unitId: g ? g.unitId : undefined, // 单位ID
        });
      }
      this.form.materialsItems[index].materials = materials;
    },
    // 删除药材
    removeRow(pIndex, cIndex) {
      this.form.materialsItems[pIndex].materials.splice(cIndex, 1);
    },
    addForBox() {
      this.form.materialsItems.push({
        acupoints: [], // 穴位
        materials: [], // 药材
      })
    },
    removeForBox(index) {
      this.form.materialsItems.splice(index, 1);
    },
    // 打开穴位选择
    openAcupointSelect(index) {
      this.currentIndex = index;

      const ids = this.form.materialsItems[index].acupoints.map(v => v.id);
      this.$refs.AcupointSelect.openModal(ids);
    },
    // 穴位选择确认
    acupointChange(nodes) {
      this.form.materialsItems[this.currentIndex].acupoints = nodes.map(v => {
        return {
          id: v.id,
          acupointName: v.label
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      const that = this;
      that.$refs["form"].validate(async (valid) => {
        if (valid) {
          const params = deepClone(that.form);
          for (let i = 0; i < params.materialsItems.length; i++) {
            const { acupoints, materials } = params.materialsItems[i];

            params.materialsItems[i].materials = materials.filter(v=> !!v.materialsId); // 清除插入的空数据

            const isApplication = params.prescriptionType == 1;
            if (acupoints.length === 0 && isApplication) {
              that.$message.error(`请在"贴${i + 1}"中添加穴位`);
              return false
            } else if (materials.length === 0) {
              that.$message.error('请添加药材');
              return false
            } else {
              const noDose = materials.find(v => !v.dose);
              if (noDose) {
                that.$message.error(`请${isApplication ? '在"贴' + (i + 1) + '"中' : ''}输入药材 (${noDose.materialsName}) 剂量`);
                return false
              }
            }


          }

          if (params.id) {
            await updatePrescript(params);
          } else {
            await addPrescript(params);
          }
          that.$message.success(params.id ? "修改成功" : "新增成功");
          that.$emit("refresh");
          that.closeModal();
        }
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.formItemTitle {
  width: 110px;
  text-align: right;
  line-height: 36px;
  color: #606266;
  padding: 0 12px 0 0;
  box-sizing: border-box;
  font-weight: 700;
}

// 贴敷样式
.forBox {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 5px;
  overflow: hidden;
  margin-top: 10px;
  .formItemTitle {
    width: 80px;
  }
  .sortTag {
    position: relative;
    top: -10px;
    left: -10px;
  }
  .forTag {
    margin: 2px;
  }
}

.menu {
  position: absolute;
  border-radius: 3px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  background-color: #fff;
  padding: 8px 0;
  z-index: 9;
}
.menu_item {
  // display: block;
  padding: 5px 60px 0px 25px;
  font-size: 12px;
  white-space: nowrap;
  cursor: pointer;
}
.menu_item:hover {
  background-color: #eee;
}
.first {
  padding-bottom: 5px;
}
.second {
  padding-top: 5px;
}
.line {
  border-bottom: 1px solid #e4e7ed;
}
</style>
